function init() {
   getSnacks();
   getNews();
}

function getNews() {
   var map = new SimpleMap();
   map.put("op", XConstants.OP_GET_NEWS);
   var request = new CustomerRequest(map.writeBody(), getNewsOver);
}

function getNewsOver(req) {
   var rsps = new Response(req.responseText);
   var map = rsps.getContent();
   var str = map.get("news");
   var s = str.substring(6, str.length - 1);
   s = s.replace(/, /g, "&");
   $("newsTitle").innerHTML = getValueFromURL(s, "title");
   $("newsContent").innerHTML = getValueFromURL(s, "content");
}

function getSnacks() {
   var map = new SimpleMap();
   map.put("op", XConstants.OP_GET_SNACKS);
   var request = new CustomerRequest(map.writeBody(), getSnacksOver, onLoading);
}

function getSnacksOver(req) {
   var rsps = new Response(req.responseText);

   if(rsps.getCode() == XConstants.SUCCESS) {
      var snacks = fixSnacks(rsps.getContent());
      showSnacks(snacks);
   }

   $("loadingSnack").className = "hidden";
}

function onLoading() {
   $("loadingSnack").className = "";
}

function showSnacks(snacks) {
   $("loadingSnack").className = "hidden";
   var keys = snacks.keys;
   var gaifan = $("gfTable").tBodies[0];
   var juanfan = $("jfTable").tBodies[0];
   var tianpin = $("tpTable").tBodies[0];
   var yinpin = $("ypTable").tBodies[0];

   for(var i = 0; i < keys.length; i++) {
      var snack = snacks.values[keys[i]];
      var row = document.createElement("tr");
      var snackName = document.createElement("td");
      snackName.innerHTML = snack.getName();
      row.appendChild(snackName);
      var snackPrice = document.createElement("td");
      snackPrice.innerHTML = snack.getPrice();
      row.appendChild(snackPrice);
//      var snackDesc = document.createElement("td");
//      snackDesc.innerHTML = snack.getDescription();
//      row.appendChild(snackDesc);
      var curTable = null;

      if(snack.getType() == XConstants.TYPE_SNACK_GAIFAN) {
         curTable = gaifan;
      }
      else if(snack.getType() == XConstants.TYPE_SNACK_JUANFAN) {
         curTable = juanfan;
      }
      else if(snack.getType() == XConstants.TYPE_SNACK_TIANPIN) {
         curTable = tianpin;
      }
      else if(snack.getType() == XConstants.TYPE_SNACK_YINPIN) {
         curTable = yinpin;
      }
      else {
         curTable = null;
      }

      if(curTable != null) {
         curTable.appendChild(row);
         row.appendChild(snackName);
         row.appendChild(snackPrice);
      }
   }
}

function fixSnacks(map) {
   var nmaps = new SimpleMap();
   var keys = map.keys;

   for(var i = 0; i < keys.length; i++) {
      if(startsWith(keys[i], "snack")) {
         var snack = new Snack();
         snack.parseString(map.get(keys[i]));
         nmaps.put(i, snack);
      }
   }

   return nmaps;
}